<template>
  <el-dialog
    v-loading="loading"
    :visible.sync="visible"
    :title="type + data.title"
    class="print-dialog"
    fullscreen
  >
    <!-- 操作栏 -->
    <div class="act-bar right">
      <CAFileCancel :documentCode="data.type" moduleCode="nursingDocument" />
      <el-button v-has="'nursingDoc:export'" type="primary" @click="dzblUpload"
        >电子病历归档</el-button
      >
      <el-button
        v-has="'nursingDoc:export'"
        type="primary"
        @click="signWithoutApperance"
        >CA认证</el-button
      >
      <el-button @click="handleClose">返 回</el-button>
      <el-button
        v-if="
          type != '打印' &&
          (!isHistory ||
            roles.includes('yx_icu_nurse') ||
            roles.includes('SUPER_ADMIN'))
        "
        type="primary"
        @click="save"
      >
        保 存
      </el-button>
      <el-button v-if="type == '打印'" type="primary" @click="handleOutput">
        导 出
      </el-button>
      <el-button
        v-if="type == '打印'"
        id="printBtn"
        v-print="printConf"
        type="primary"
      >
        打 印
      </el-button>
    </div>
    <div class="clearfix"></div>
    <!-- <div class="time-picker">
      创建时间
      <DateSelection
        v-model="createTime"
        style="margin-left: 20px"
        :simple-op="true"
        :date-picker-show="true"
        :date-show="true"
        :picker-options="pickerOptions"
        :no-clear="true"
        @onchange="handleCreateTimeChange"
      />
    </div> -->
    <component
      :is="data.formComp"
      ref="docPage"
      :data="data"
      :records="records"
      :type="type"
      :form-type="formType"
      @setCanOperate="setCanOperate"
    />
  </el-dialog>
</template>

<script>
import { endOfDay, startOfDay } from 'date-fns'
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  toRefs,
  watch
} from 'vue'

import { Doc } from '@/api/doc/index'
import CAFileCancel from '@/components/CAFileCancel/index.vue'
import DateSelection from '@/components/DateSelection/indexV2.vue'
import { useCA } from '@/hooks'
import {
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import { useDocExport } from '../hooks'
import BloodSupplyObserve from './BloodSupplyObserve/index.vue'
import CBP from './CBP/index.vue'
import DifficultConsultation from './DifficultConsultation/index.vue'
import EndoscopeOperate from './EndoscopeOperate/index.vue'
import FallMonitoring from './FallMonitoring/index.vue'
import HandoverRecord from './HandoverRecord/index.vue'
import HealthEducation from './HealthEducation/index.vue'
import InterveneHandover from './InterveneHandover/index.vue'
import MissuctionRisk from './MissuctionRisk/index.vue'
import PICC from './PICC/index.vue'
import PICCRisk from './PICCRisk/index.vue'
import PressureApplication from './PressureApplication/index.vue'
import PressureMonitoring from './PressureMonitoring/index.vue'
import RyAdultEstimate from './RyAdultEstimate/index.vue'
import SurgicalHandover from './SurgicalHandover/index.vue'
import TCMNursingDialectical from './TCMNursingDialectical/index.vue'
import Vte from './Vte/index.vue'

export default defineComponent({
  name: 'PrintDialog',
  components: {
    DateSelection,
    BloodSupplyObserve,
    CBP,
    TCMNursingDialectical,
    Vte,
    FallMonitoring,
    PressureMonitoring,
    HealthEducation,
    MissuctionRisk,
    RyAdultEstimate,
    PressureApplication,
    HandoverRecord,
    EndoscopeOperate,
    SurgicalHandover,
    InterveneHandover,
    CAFileCancel,
    PICC,
    PICCRisk,
    DifficultConsultation
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['refresh'],
  setup(props, { emit }) {
    const state = reactive({
      printConf: {
        id: 'printDom',
        popTitle: '打印', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {}, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: ''
      },
      visible: false,
      loading: false,
      type: '',
      records: [],
      createTime: null,
      formType: 'add',
      pickerOptions: {},
      operateType: '', // 操作类型
      canOperate: false, // 用来判断是否能执行自动打印
      printTimer: null, // 定时器对象
      docPage: {}
    })

    const { handleDocExportMulti } = useDocExport()
    const store = getStoreFromInstance()
    const CA = useCA()
    const { $message, $notify } = getElementFnFromInstance()

    const patCur = computed(() => store.getters.patCur)

    const user = computed(() => store.getters.user)

    const roles = computed(() => store.getters.roles)

    const isHistory = computed(() => store.getters.isHistory)

    function setCanOperate(f) {
      state.canOperate = f
    }

    function setOperateType(t) {
      state.operateType = t
    }

    function printDoc() {
      if (state.visible && state.canOperate && !state.printTimer) {
        state.printTimer = setTimeout(() => {
          if (state.operateType == 'print') {
            state.loading = false
            document.querySelector('#printBtn').click()
          } else if (state.operateType == 'output') {
            handleOutput()
          } else if (state.operateType == 'sign-without') {
            signWithoutApperance()
          } else if (state.operateType == 'dzbl') {
            dzblUpload()
          }
          state.printTimer = null
        }, 200)
      }
    }

    function handleCreateTimeChange(e) {
      if (!patCur.value) {
        return
      }
      if (patCur.value.startRkTime && e < patCur.value.startRkTime) {
        state.createTime = patCur.value.startRkTime
      } else if (patCur.value.endCkTime && e > patCur.value.endCkTime) {
        state.createTime = patCur.value.endCkTime
      }
    }

    async function initEditData(id, type = 'add') {
      state.formType = type
      const patCur = store.getters.patCur

      if (id) {
        //修改
        const { data } = await Doc.getInfo(id)
        state.type = type == 'edit' ? '修改' : '新增'
        if (type == 'add') {
          delete data.id
          delete data.createdBy
          delete data.createTime
          delete data.updatedBy
          delete data.updateTime
        }
        state.records = [data]
      } else {
        //新增
        state.type = '新增'
        state.records = [{ jsonText: null }]
      }
      state.createTime = patCur.endCkTime
        ? patCur.endCkTime
        : new Date().getTime()
      state.visible = true
    }

    function initPreviewData(list) {
      state.visible = true
      state.loading = true
      state.records = list.length > 0 ? list : [{ jsonText: null }]
      state.type = '打印'
      nextTick(() => {
        printDoc()
      })
    }

    async function save() {
      const form = state.docPage.getParams() || {}
      if (form.createTime) {
        // form.createTime = new Date(form.createTime).getTime();
        form.createTime = state.createTime
      }
      // 修改
      if (form.id) {
        await Doc.edit(form)
      } else {
        // 新增
        const params = {
          id: '',
          patientIdent: patCur.value.patientIdent,
          gender: patCur.value.gender,
          jsonText: form.jsonText,
          type: props.data.type,
          bedNumber: patCur.value.bedNumber,
          patientName: patCur.value.patientName,
          wardName: patCur.value.wardName,
          hospitalNumber: patCur.value.hospitalNumber,
          docName: props.data.title,
          createTime: state.createTime
        }
        await Doc.add(params)
      }
      $message.success(`保存成功`)
      handleClose()
    }

    function handleClose() {
      state.visible = false
      state.records = []
      setOperateType('')
      emit('refresh')
    }

    function handleOutput() {
      state.loading = true
      handleDocExportMulti(
        state.docPage.returnDom(),
        props.data.horizontal ? 'landscape' : '',
        props.data.title + '.pdf',
        () => {
          state.loading = false
        }
      )
    }

    function signWithoutApperance() {
      state.loading = true
      CA.signWithoutApperance(
        state.docPage.returnDom(),
        props.data.horizontal ? 'landscape' : '',
        props.data.title + '.pdf',
        'nursingDocument',
        props.data.type,
        () => {
          state.loading = false
        }
      )
    }

    function dzblUpload() {
      state.loading = true
      CA.dzblUpload(
        state.docPage.returnDom(),
        props.data.horizontal ? 'landscape' : '',
        props.data.title + '.pdf',
        'nursingDocument',
        props.data.type,
        () => {
          state.loading = false
        }
      )
    }

    watch(
      () => props.data.formComp,
      (n, o) => {
        if (n != o) {
          setCanOperate(false)
        }
      }
    )

    watch(
      () => state.canOperate,
      n => {
        if (n) {
          printDoc()
        }
      }
    )

    return {
      ...toRefs(state),
      isHistory,
      user,
      roles,
      initPreviewData,
      initEditData,
      setOperateType,
      handleClose,
      save,
      handleOutput,
      handleCreateTimeChange,
      setCanOperate,
      signWithoutApperance,
      dzblUpload
    }
  }
})
</script>

<style lang="scss" scoped>
.time-picker {
  display: flex;
  align-items: center;
  width: 210mm;
  margin: 0 auto 10px;
}

.doc-container {
  font-family: Tahoma, Arial, SimSun, '宋体', 'Microsoft YaHei', '微软雅黑',
    sans-serif;
  margin: 0 auto;
  width: 210mm;
  height: 297mm;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #f0f0f0;
}

::v-deep {
  .el-dialog__body {
    color: #000;
  }
}
</style>
./FallMonitoring/index.vue
